package com.bluedot.www.core.filter;

import com.bluedot.www.core.pojo.DO.Right;
import com.bluedot.www.core.pojo.DO.User;
import com.bluedot.www.core.pojo.DTO.R;
import com.bluedot.www.core.pojo.DTO.RightJudgeDTO;
import com.bluedot.www.core.pojo.DTO.UserDTO;
import com.bluedot.www.core.service.RightService;
import com.bluedot.www.framework.mvc.servlet.http.HttpMessageConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ZhouXuan
 * @version 1.0
 * @date 2021/8/18 20:49
 */
public class RightFilter implements Filter {

    private static final String PROJECT_NAME = "handwritingAnalysisSys_Web_exploded";

    /**
     * 日志，用于记录特定系统或应用的消息
     */
    Logger logger = LoggerFactory.getLogger(RightFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        // 过滤
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", "*");//  这里最好明确的写允许的域名
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token,Authorization,ybg");
        // 注释父类实现，否则报错：405 HTTP method GET is not supported by this URL
        logger.info("执行了过滤方法");

        // 设置响应数据格式
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        R result = null;

        // 获取访问路径
        String reqURL = request.getRequestURI();
        int index = reqURL.indexOf(PROJECT_NAME) + PROJECT_NAME.length();
        String reqPath = reqURL.substring(index);

        // 判断当前访问资源都是在权限容器中
        Right right = (Right) RightService.execute("findRightByUrl", new Object[]{reqPath});
        if (right == null) {
            // 不在受控制权限中，允许通过
            chain.doFilter(request, res);
            return;
        }

        //先判断用户是否登录
        // 需要注意的地方是request.getSession() 等同于 request.getSession(true)，除非我们确认session一定存在或者session不存在时明确有创建session的需要，否则尽量使用request.getSession(false)。
        HttpSession session = request.getSession(false);
        if (session == null) {
            // 会话已经失效或者未登录，需要重定向到登录页面
            result = R.error().message("会话已经失效或者未登录，需要重定向到登录页面！！");
            response.getWriter().write(HttpMessageConverter.toJson(result));
            return;
        }

        // 登录时将用户作为对象存入session中，key为SESSION_KEY_USER
        UserDTO UserDTO = (UserDTO) session.getAttribute("SESSION_KEY_USER");
        User user = UserDTO.getUser();


        //判断用户是否被封禁
        if (user.getStatus() == 1) {
            result = R.error().message("用户已被封禁，请及时联系管理员！！");
            response.getWriter().write(HttpMessageConverter.toJson(result));
            return;
        }

        // 调用service方法
        if (user != null) {
            try {
                RightJudgeDTO rightJudgeDTO = new RightJudgeDTO();
                rightJudgeDTO.setReqPath(reqPath);
                rightJudgeDTO.setUserDTO(UserDTO);
                boolean flag = (boolean) RightService.execute("judgeUserCanAccess", new Object[]{rightJudgeDTO});
                if (flag) {
                    chain.doFilter(request, response);
                } else {
                    result = R.error().message("权限不足，请切换用户！！！");
                    response.getWriter().write(HttpMessageConverter.toJson(result));
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void destroy() {

    }
}
